﻿package  Welsy4.Connect.commands
{
	
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	
	import Welsy4.Connect.vo.HttpServiceHandler;
	import Welsy4.Connect.vo.User;
	
	import mx.controls.Alert;
	
	import mx.rpc.IResponder;
	import Welsy4.Connect.model.ConnectModel;
	import Welsy4.Connect.events.ChainEvent;
	import Welsy4.Connect.events.ResponseEvent;
	import Welsy4.Connect.business.AuthenticationDelegate;
	
	public class SecureLoginCommand extends SequenceCommand implements ICommand, IResponder
	{
		
		public function SecureLoginCommand() 
		{
			
		}
		override public function execute(event:CairngormEvent):void {
		    ConnectModel.getInstance().addQueue("SecureLoginCommand.execute");
			this.nextEvent = ChainEvent(event).nextChainedEvent;
			
			//il controller esegue questo metodo quando intercetta l'evento 
			var delegate : AuthenticationDelegate = new AuthenticationDelegate(this);
			delegate.SecureLogin(ChainEvent(event).eventRequest.login,ChainEvent(event).eventRequest.password);
			
			var currentUser:User = new User(ChainEvent(event).eventRequest.login);
			currentUser.permission = User.HOST;
			currentUser.setPassword(ChainEvent(event).eventRequest.password);
			currentUser.isAdministrator = true;
			
			ConnectModel.getInstance().currentUser = currentUser;
		}
		
		public function result(event:Object):void {
			
			// listen for ok result
			ConnectModel.getInstance().addQueue("SecureLoginCommand.result " + event.result);
			
			ConnectModel.getInstance().httpServiceHandler = new HttpServiceHandler();
			ConnectModel.getInstance().httpServiceHandler.setXML(event.result);
			
			if (ConnectModel.getInstance().httpServiceHandler.getResultStatus() == ConnectModel.SESSION_OK) {
				//Alert.show("Admin logged in" + "\n\n" + "BREEZESESSION: " + ConnectModel.getInstance().sessionCookie);
				ConnectModel.getInstance().currentUser.validUser = true;
				CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.LOGGED_IN,true, ResponseEvent.OK, event.result));
			    this.executeNextCommand();
			} else {
				CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR,true,ResponseEvent.NO_DATA,event.result));
				
			}
			
		    
		    	
			
		}
		
		public function fault(event:Object):void {
			// listen for fault result
			ConnectModel.getInstance().addQueue("SecureLoginCommand.fault");
		}
	}
	
}